package com.shanling.shanlingcontroller.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chipsguide.lib.bluetooth.managers.BluetoothDeviceManager;
import com.linkplay.lpvr.avslib.LPAVSManager;
import com.linkplay.lpvr.blelib.manager.LPAVSBTManager;
import com.linkplay.lpvr.lpvrbean.BaseDevice;
import com.linkplay.lpvr.lpvrlistener.DeviceListener;
import com.shanling.shanlingcontroller.CustomApplication;
import com.shanling.shanlingcontroller.R;
import com.shanling.shanlingcontroller.adapter.CommonAdapter;
import com.shanling.shanlingcontroller.adapter.ViewHolder;
import com.shanling.shanlingcontroller.base.BaseAppCompatActivity;
import com.shanling.shanlingcontroller.base.BaseAppManager;
import com.shanling.shanlingcontroller.base.BaseMVPActivity;
import com.shanling.shanlingcontroller.bean.BluetoothState;
import com.shanling.shanlingcontroller.bean.Constants;
import com.shanling.shanlingcontroller.bean.EventCenter;
import com.shanling.shanlingcontroller.bean.MybluetoothDevice;
import com.shanling.shanlingcontroller.persenter.BlePersenter;
import com.shanling.shanlingcontroller.persenter.contract.BleContract;
import com.shanling.shanlingcontroller.utils.BluetoothUtil;
import com.shanling.shanlingcontroller.utils.ToastUtils;
import com.shanling.shanlingcontroller.utils.netstatus.NetUtils;
import com.shanling.shanlingcontroller.view.DiffuseView;
import com.shanling.shanlingcontroller.view.MyDilalogUtils;
import com.shanling.shanlingcontroller.view.NoChooseDialog;


import org.litepal.LitePal;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;

public class BleActivity extends BaseMVPActivity<BleContract.Presenter> implements MyDilalogUtils.OnDialogClickListener, BleContract.View, AdapterView.OnItemClickListener, BluetoothDeviceManager.OnBluetoothDeviceDiscoveryListener {
    @BindView(R.id.diffuseView)
    DiffuseView diffuseView;
    @BindView(R.id.iv_ble)
    ImageView ivBle;
    @BindView(R.id.lv_ble)
    ListView lvBle;
    @BindView(R.id.bt_ble)
    Button btBle;
    @BindView(R.id.pb_ble)
    ProgressBar pbBle;
    @BindView(R.id.tv_ble)
    TextView tvBle;
    private MyDilalogUtils dilalogUtils;
    private final int REQUEST_ENABLE_BT = 101;
    private final int REQUST_LOACTIONPERIMISSON = 100;
    private final int REQUST_LOACTIONSERVER = 102;
    private BluetoothDeviceManager bluetoothDeviceManager;
    private List<MybluetoothDevice> devices;
    private CommonAdapter<MybluetoothDevice> mybluetoothDeviceCommonAdapter;
    private MybluetoothDevice mycheckDevice;
    private boolean isconnected = false;
    private Runnable runnable;
    private boolean isonResume = false;
    private NoChooseDialog noChooseDialog;

    @Override
    protected void getBundleExtras(Bundle extras) {
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_ble;
    }

    @Override
    protected void initViewsAndEvents() {
        bluetoothDeviceManager = CustomApplication.getInstance().getBluetoothDeviceManager();
        if (bluetoothDeviceManager != null) {
            bluetoothDeviceManager.setOnBluetoothDeviceDiscoveryListener(this);
        }
        dilalogUtils = new MyDilalogUtils(this, R.style.myDialog, getString(R.string.location_permission_need), getString(R.string.this_app_need_location_permission_scan));
        dilalogUtils.setOnDialogClickListener(this);
        devices = new ArrayList<>();
        mybluetoothDeviceCommonAdapter = new CommonAdapter<MybluetoothDevice>(this, devices, R.layout.item_ble) {
            @Override
            public void convert(ViewHolder helper, int position, MybluetoothDevice item) {
                TextView textView = helper.getView(R.id.tv_blename);
                textView.setText(item.getName() + "(" + item.getMac() + ")");
                if (item.isIscheck()) {
                    textView.setBackgroundResource(R.drawable.item_check);
                } else {
                    textView.setBackgroundResource(R.drawable.item_nor);
                }
            }
        };
        lvBle.setAdapter(mybluetoothDeviceCommonAdapter);
        lvBle.setOnItemClickListener(this);
        runnable = new Runnable() {
            @Override
            public void run() {
                if (customApplication.isConnected()) {
                    return;
                }
                ToastUtils.showLongToast(BleActivity.this, R.string.conntect_timeout);
                isconnected = false;
                pbBle.setVisibility(View.INVISIBLE);
                tvBle.setVisibility(View.INVISIBLE);
                btBle.setVisibility(View.VISIBLE);
            }
        };
        noChooseDialog = new NoChooseDialog(this, R.style.myDialog, R.string.Bluetooth_disable, R.string.ble_diloghint, R.string.turnon_Bluetooth, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                noChooseDialog.dismiss();

            }
        });
        checkBleEnable();
    }

    private void checkBleEnable() {
        if (BluetoothUtil.isBluetoothEnable()) {
            mPersenter.checkAppPermission(this);
        } else {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }

    @Override
    protected void initData() {
    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    @Override
    protected void onEventComing(EventCenter eventCenter) {
        switch (eventCenter.getEventCode()) {
            case Constants.A2DP_ISCONNTECT:
                boolean isConntect = (boolean) eventCenter.getData();
                if (isConntect) {
                    doConnectSpp();
                }
                break;
            case Constants.IS_BOND:
                boolean isbond = (boolean) eventCenter.getData();
                if(isbond){
                   mPersenter.doConnectA2dp(mycheckDevice.getBluetoothDevice());
                }
                break;
            case Constants.BLUETOOTH_STATE:
                BluetoothState state = (BluetoothState) eventCenter.getData();
                if (state == null) {
                    return;
                }
                switch (state.getState()) {
                    case Constants.CONNECTED:
                        mHandler.removeCallbacks(null);
                        readyGoThenKill(MainActivity.class);
                        break;
                }
        }
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    public void onSure() {
        // 去应用信息
        Intent localIntent = new Intent();
        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        startActivityForResult(localIntent, REQUST_LOACTIONPERIMISSON);
    }

    @Override
    public void onCancel() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_ENABLE_BT:
                    mPersenter.checkAppPermission(BleActivity.this);
                    break;
                case REQUST_LOACTIONPERIMISSON:
                    checkServer();
                    break;
                case REQUST_LOACTIONSERVER:
                    isScan(true);
                    break;
            }
        }
    }


    public boolean isLocServiceEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    public void checkServer() {
        if (isLocServiceEnable(BleActivity.this)) {
            isScan(true);
        } else {
            ToastUtils.showToast(BleActivity.this, R.string.open_locationservice);
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, REQUST_LOACTIONSERVER);
        }
    }

    @OnClick({R.id.iv_ble, R.id.bt_ble})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_ble:
                if (isconnected) {
                    ToastUtils.showToast(this, R.string.conntected);
                } else {
                    ToastUtils.showToast(this, R.string.Searching);
                    checkBleEnable();
                }
                break;
            case R.id.bt_ble:
                doConnectedA2dp();
                break;
        }
    }


    //分类型连接
    private void doConnectedA2dp() {
        if (mycheckDevice != null) {
            isconnected = true;
            if (bluetoothDeviceManager.isDiscovering()) {
                bluetoothDeviceManager.cancelDiscovery();
            }
            mHandler.removeCallbacks(null);
            btBle.setVisibility(View.GONE);
            tvBle.setText(R.string.conntected);
            pbBle.setVisibility(View.VISIBLE);
            tvBle.setVisibility(View.VISIBLE);
            mPersenter.doBand(mycheckDevice.getBluetoothDevice(),mycheckDevice.getType(),this);
            mHandler.postDelayed(runnable, 15* 1000);
        }
    }

    public void doConnectSpp(){
        if(mycheckDevice==null){
            return;
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.e("weiyu","连接spp");
                mPersenter.doConnectSpp(mycheckDevice.getBluetoothDevice(), mycheckDevice.getType(),BleActivity.this );
            }
        },6500);
    }
    public void isScan(boolean scan) {
        if (scan) {
            btBle.setVisibility(View.GONE);
            tvBle.setVisibility(View.VISIBLE);
            tvBle.setText(R.string.Searching);
            pbBle.setVisibility(View.VISIBLE);
            diffuseView.setVisibility(View.VISIBLE);
            diffuseView.start();
            devices.clear();
            mybluetoothDeviceCommonAdapter.refresh(devices);
            if (bluetoothDeviceManager != null) {
                bluetoothDeviceManager.startDiscovery();
            }
        } else {
            if (!isconnected) {
                tvBle.setVisibility(View.INVISIBLE);
                pbBle.setVisibility(View.INVISIBLE);
            }
            diffuseView.setVisibility(View.INVISIBLE);
            diffuseView.stop();
        }
    }

    @Override
    public void getPermissonSuccess() {
        checkServer();
    }

    @Override
    public void getPermissonFaild() {
        dilalogUtils.show();
        dilalogUtils.setCancelable(false);
    }
    @Override
    public void onBluetoothDeviceDiscoveryStarted() {

    }
    @Override
    public void onBluetoothDeviceDiscoveryFound(BluetoothDevice bluetoothDevice) {
        String name = bluetoothDevice.getName();
        if (TextUtils.isEmpty(name) || !isonResume||name.contains("BLE")) {
            return;
        }
        Log.e("weiyu","搜到"+name);
        if (name.startsWith("US1") || name.startsWith("US1i") || name.startsWith("Shan")) {
            MybluetoothDevice device = new MybluetoothDevice();
            int bleType = getBleType(bluetoothDevice.getName());
            device.setBluetoothDevice(bluetoothDevice);
            device.setType(bleType);
            device.setIscheck(false);
            device.setName(bluetoothDevice.getName());
            device.setMac(bluetoothDevice.getAddress());
            if (!devices.contains(device)) {
                devices.add(device);
                mybluetoothDeviceCommonAdapter.refresh(devices);
            }
        }
    }

    @Override
    public void onBluetoothDeviceDiscoveryFinished() {
        if (!isonResume) {
            return;
        }
        if (isconnected) {
            diffuseView.setVisibility(View.INVISIBLE);
            diffuseView.stop();
        } else {
            isScan(false);
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        for (int i = 0; i < devices.size(); i++) {
            devices.get(i).setIscheck(false);
        }
        devices.get(position).setIscheck(true);
        mybluetoothDeviceCommonAdapter.refresh(devices);
        if (isconnected) {
            ToastUtils.showToast(this, R.string.conntected);
        } else {
            isScan(false);
            btBle.setVisibility(View.VISIBLE);
            mycheckDevice = devices.get(position);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isonResume = false;
        if (diffuseView.isDiffuse()) {
            isScan(false);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isonResume = true;
    }


    @Override
    protected void onBleStateOff() {
        super.onBleStateOff();
        isScan(false);
        noChooseDialog.show();
    }

    @Override
    protected void onBleStateOn() {
        super.onBleStateOn();
        noChooseDialog.dismiss();
        checkBleEnable();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        mPersenter.onFinish();
    }
    @Override
    protected BleContract.Presenter createPresenter() {
        return new BlePersenter(this);
    }

    private int getBleType(String name) {
        if (name.startsWith("US1i")) {
            return 1;
        }
        if (name.startsWith("US1")) {
            return 2;
        }
        if (name.startsWith("Shan")) {
            return 3;
        }
        return 1;
    }
}
